#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <mysql/mysql.h>

#include "dbcom.h"
#include "dbfunc.h"

static char *username="dbuser";
static char *password="mysql";
static char *dbname="data";
thrd_conn_t a_thrd_conn[CONNECT_QT];


void checkerr(MYSQL *sock, unsigned int *errcode)
{
    unsigned int result=mysql_errno(sock);

    if(result)
    {
        printf("errno:%d errmsg:%s\n", result, mysql_error(sock));
    }
    *errcode=result;
}
    

void DbsInit()
{
    int thrd_index;

    for(thrd_index=0; thrd_index<CONNECT_QT; thrd_index++)
    {   
        ThrdConn.sock=(MYSQL *)NULL;
    }

    return;
}


int DbsConnect(int thrd_index)
{
    DEFAULT_DEFINITION;

    mysql_init(&ThrdConn.mysql);
    if(!(ThrdConn.sock=mysql_real_connect(&ThrdConn.mysql, NULL,
            username, password, dbname, 0, NULL, 0)) ||
       !(ThrdConn.sql=(char *)malloc(SQL_BUF_LEN)))
    {
        printf("DbsConnect:thread=%d connect fail\n", thrd_index);
        return(DB_ERROR);
    }

    return(DB_OK);
}


void DbsDisConnect(int thrd_index)
{
    if(ThrdConn.sock)
    {
        mysql_close(ThrdConn.sock);
        ThrdConn.sock=(MYSQL *)NULL;
        free(ThrdConn.sql);
    }
    return;
}


void DbsDisConnectAll()
{
    int thrd_index;

    for(thrd_index=0; thrd_index<CONNECT_QT; thrd_index++)
        DbsDisConnect(thrd_index);

    return;
}


void DbsCommit(int thrd_index)
{
    return;
}


void DbsRollback(int thrd_index)
{
    return;
}


int DbsSQLExec(int thrd_index, char *sql)
{
    DEFAULT_DEFINITION;

    if(mysql_query(ThrdConn.sock, sql))
        ReturnErr;

    return(DB_OK);
}
